package com.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.pojo.*;
import com.service.CommodityService;
import com.service.IndentService;
import com.service.RoleService;
import com.util.DateUtil;
import com.util.LayuiTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@Transactional
@RequestMapping("/indent")
public class IndentController {
    @Autowired
    public IndentService indentService;
    @Autowired
    public RoleService roleService;
    @Autowired
    public CommodityService commodityService;
//    查询经理审批订单
    @RequestMapping("/managerlist")
    @ResponseBody
    public String indentManagerList(String ename, Integer iid,String firm,HttpSession session){
        Integer empid= (Integer) session.getAttribute("loginEmpno");
        Integer roleid=roleService.CERselectEmpid(empid).get(0).getRoleid();
        return JSON.toJSONString(LayuiTable.tableData(indentService.indentFindManager(ename,iid,firm,2).size(),
                 indentService.indentFindManager(ename,iid,firm,2)), SerializerFeature.DisableCircularReferenceDetect);
    }

    //查询所有订单
    @RequestMapping("/list")
    @ResponseBody
    public String indentList(String ename, Integer iid,String firm){
        return JSON.toJSONString(LayuiTable.tableData(indentService.indentFindAll(ename,iid,firm).size(),
                indentService.indentFindAll(ename,iid,firm)), SerializerFeature.DisableCircularReferenceDetect);
    }

    //    查询老板审批订单
    @RequestMapping("/bosslist")
    @ResponseBody
    public String indentBossList(String ename, Integer iid,String firm,HttpSession session){
        Integer empid= (Integer) session.getAttribute("loginEmpno");
        Integer roleid=roleService.CERselectEmpid(empid).get(0).getRoleid();
        return JSON.toJSONString(LayuiTable.tableData(indentService.indentFindBoss(ename,iid,firm,roleid).size(),
                indentService.indentFindBoss(ename,iid,firm,roleid)), SerializerFeature.DisableCircularReferenceDetect);
    }

    //采购员只能查看自己提交的订单
    @RequestMapping("/buyerlist")
    @ResponseBody
    public String indentBuyerList(String ename, Integer iid,String firm,HttpSession session){
        Integer empno= (Integer) session.getAttribute("loginEmpno");
        return JSON.toJSONString(LayuiTable.tableData(indentService.indentFindBuyer(ename,iid,firm,empno).size(),
                indentService.indentFindBuyer(ename,iid,firm,empno)), SerializerFeature.DisableCircularReferenceDetect);
    }

//    查询商品类别
@RequestMapping("/classifylist")
@ResponseBody
public String classify(Integer tid){
    return JSON.toJSONString(LayuiTable.tableData(commodityService.classifySelect(tid).size(),
            commodityService.classifySelect(tid)), SerializerFeature.DisableCircularReferenceDetect);
}

//    创建订单
    @RequestMapping("/add")
    @ResponseBody
    public String indentadd(HttpSession session,String indentlist){
        Map add= JSON.parseObject(indentlist);
        List<Measurement> measurements=indentService.measurementSelect(null,null,null,null);
        Integer mid=1;
        String mbig= add.get("mbig").toString();
        Integer scale= Integer.valueOf(add.get("scale").toString());
        String mlittle= add.get("mlittle").toString();
        int a=0;
        if (measurements.size()==0){
            Measurement measurement=new Measurement(mid,mbig,scale,mlittle);
            a=indentService.measurementInsert(measurement);
        }else {
            if (indentService.measurementSelect(null,mbig,scale,mlittle).size()==0){
                mid= measurements.get(measurements.size()-1).getMid()+1;
                Measurement measurement=new Measurement(mid,mbig,scale,mlittle);
                a=indentService.measurementInsert(measurement);
            }else {
                mid=indentService.measurementSelect(null,mbig,scale,mlittle).get(0).getMid();
                a=1;
            }
        }
        List<State> states=indentService.stateSelect(null);
        Integer staid=1;
        if (states.size()!=0){
            staid= states.get(states.size()-1).getStaid()+1;
        }
        int b=indentService.stateInsert(staid);
        List<Indent> indents=indentService.indentSelect(null);
        Integer iid=1;
        if (indents.size()!=0){
            iid= indents.get(indents.size()-1).getIid()+1;
        }
        Object loginEmpno=session.getAttribute("loginEmpno");
        Integer initiator= (Integer) loginEmpno;
        String cname= add.get("cname").toString();
        Integer tid= Integer.valueOf(add.get("tid").toString());
        double price= Double.parseDouble(add.get("price").toString());
        Integer num= Integer.valueOf(add.get("num").toString());
        Integer sid= Integer.valueOf(add.get("sid").toString());
        Indent indent=new Indent(iid,initiator,cname,tid,mid,BigDecimal.valueOf(price),num,null,staid,sid,null);
        int c=indentService.indentInsert(indent);
        if (a+b+c==3){
            return "true";
        }else {
            return "false";
        }
    }
    //    老板or经理审批修改
    @RequestMapping("/examineUpd")
    @ResponseBody
    public String examinerUpd(HttpSession session,@RequestParam("iid") Integer iid,@RequestParam(value = "manager",required = false) Integer manager,@RequestParam(value = "payment",required = false)Integer payment,@RequestParam("rank") Integer rank){
        List<Indent> indents=indentService.indentSelect(iid);
        Integer staid=indents.get(0).getStaid();
        int a=indentService.rankUpd(iid,rank);
        int b=indentService.managerUpd(staid, manager,payment);
        List<Agreer> agreers=indentService.agreerSelect(null);
        Integer agrid=1;
        if (agreers.size()!=0){
            agrid= agreers.get(agreers.size()-1).getAgrid()+1;
        }
        Object loginEmpno=session.getAttribute("loginEmpno");
        Integer appno= (Integer) loginEmpno;
        int c=indentService.agreerInsert(new Agreer(agrid,iid,appno));
        if (a+b+c==3){
            return "true";
        }else {
            return "false";
        }
    }


    //修改订单数量
    @RequestMapping("/indentUpdNum")
    @ResponseBody
    public String indentUpdNum(@RequestParam("iid") Integer iid,@RequestParam("num") Integer num){
        if (indentService.indentUpdNum(iid, num)==1){
            return "true";
        }else {
            return "false";
        }
    }

    //修改交货日期
    @RequestMapping("/indentUpdDt")
    @ResponseBody
    public String indentUpdDt(Integer iid,String deliveryTime) throws ParseException {
        Integer staid=indentService.indentSelect(iid).get(0).getStaid();
        SimpleDateFormat bjSdf = new SimpleDateFormat("yyyy-MM-dd");
        bjSdf.setTimeZone(TimeZone.getTimeZone("GMT+08"));
        Date dtime = bjSdf.parse(deliveryTime);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(dtime);
        calendar.add(calendar.DATE,1); //把日期往后增加一天,整数  往后推,负数往前移动
        dtime=calendar.getTime();
        System.out.println("交货时间"+dtime);

        if (indentService.indentUpdDt(staid, dtime)==1){
            return "true";
        }else {
            return "false";
        }
    }


    //    订单确认，等待付款
    @RequestMapping("/UpdAffirm")
    @ResponseBody
    public String indentUpdAffirm(Integer iid) {
        if (indentService.indentUpdAffirm(iid,3)==1){
            return "true";
        }else {
            return "false";
        }
    }

    //    财务查看订单
    @RequestMapping("/FindFinance")
    @ResponseBody
    public String indentFindFinance(HttpSession session){
        Integer empid= (Integer) session.getAttribute("loginEmpno");
        Integer roleid=roleService.CERselectEmpid(empid).get(0).getRoleid();
        return JSON.toJSONString(LayuiTable.tableData(indentService.indentFindFinance(9).size(),
                indentService.indentFindFinance(9)), SerializerFeature.DisableCircularReferenceDetect);
    }

    //        财务确认，付款完成
    @RequestMapping("/stateUpdPayment")
    @ResponseBody
    public String stateUpdPayment(Integer iid) {
        Integer staid=indentService.indentSelect(iid).get(0).getStaid();
        int a=indentService.stateUpdPayment(staid,2);
        int b=indentService.indentUpdAffirm(iid,4);
        if (a+b==1){
            return "true";
        }else {
            return "false";
        }
    }

    //    取消订单
    @RequestMapping("/del")
    @ResponseBody
    public String indentaDel(@RequestParam("iid") Integer iid){
        List<Indent> indents=indentService.indentSelect(iid);
        Integer mid= indents.get(0).getMid();
        Integer staid=indents.get(0).getStaid();
        int a=indentService.indentDel(iid);
        int b=indentService.measurementDel(mid);
        int c=indentService.stateDel(staid);
        if (a+b+c==1){
            return "true";
        }else {
            return "false";
        }
    }

    //    保管员可查看订单
    @RequestMapping("/verify")
    @ResponseBody
    public String indentVerify(HttpSession session){
        Integer empid= (Integer) session.getAttribute("loginEmpno");
        Integer roleid=roleService.CERselectEmpid(empid).get(0).getRoleid();
        return JSON.toJSONString(LayuiTable.tableData(indentService.indentVerify(7).size(),
                indentService.indentVerify(7)), SerializerFeature.DisableCircularReferenceDetect);
    }

    //实际到货
    @RequestMapping("/updFact")
    @ResponseBody
    public String indentUpdFact(@RequestParam("iid") Integer iid,@RequestParam("fact") Integer fact) {
        if (indentService.indentUpdFact(iid, fact)==1){
            return "true";
        }else {
            return "false";
        }
    }

    //    保管员确认
    @RequestMapping("/storage")
    @ResponseBody
    public String storage(HttpSession session,@RequestParam("iid") Integer iid) throws ParseException {
        Integer empid= (Integer) session.getAttribute("loginEmpno");
        Integer staid=indentService.indentSelect(iid).get(0).getStaid();
        int a=indentService.indentUpdAffirm(staid,5);
        SimpleDateFormat bjSdf = new SimpleDateFormat("yyyy-MM-dd");
        bjSdf.setTimeZone(TimeZone.getTimeZone("GMT+08"));
        Date endTime = bjSdf.parse(DateUtil.getCurrentDate());
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(endTime);
        calendar.add(calendar.DATE,1); //把日期往后增加一天,整数  往后推,负数往前移动
        endTime=calendar.getTime();
        int b=indentService.stateUpdRVEE(staid,empid,endTime);
        List<Commodity> commodities=commodityService.commodityFindAll(null,null,null);
        Integer cid=1;
        int c=0;
        Indent indentlist=indentService.indentSelect(iid).get(0);
        String cname=indentlist.getCname();
        Integer tid=indentlist.getTid();
        BigDecimal cprice=indentlist.getPrice();
        Integer mid=indentlist.getMid();
        Integer count=indentlist.getFact();
        Integer sid=indentlist.getSid();
        if (commodities.size()==0){
            Commodity commodity=new Commodity(cid,cname,new Classify(tid,null),cprice,null,
                    new Measurement(mid,null,null,null),count,
                    new Suppiler(sid,null,null,null,null,null,null,null),0);
            c=commodityService.commodityInsert(commodity);
        }else {
            int IU=1;
            for (Commodity commoditylist:commodities
                 ) {
                String getCname = commoditylist.getCname();
                Integer getSid = commoditylist.getSids().getSid();
                BigDecimal getCprice = commoditylist.getCprice();
                Integer getMid = commoditylist.getMids().getMid();
                if (cname.equals(getCname) && sid == getSid && cprice.compareTo(getCprice)==0 && mid == getMid){
                    IU=IU+1;
                    cid=commoditylist.getCid();
                    Commodity findCount=commodityService.commodityFindByCid(cid).get(0);
                    Integer finallycount=findCount.getCount()+count;
                    c=commodityService.commodityUpdCount(cid,finallycount);
                    int upda=0;
                    int updb=0;
                    for (Commodity commodityUpdlist:commodityService.commodityFindAll(null,null,null)
                    ) {
                        if (commodityUpdlist.getSprice()!=null){
                            if (commodityUpdlist.getSprice().compareTo(BigDecimal.valueOf(0))==1){
                                System.out.println("进入if");
                                Integer updcid=commodityUpdlist.getCid();
                                Commodity commoditys=commodityService.commodityFindAll(updcid,null,null).get(0);
                                Integer updscale=commoditys.getMids().getScale();
                                Integer updcount=commoditys.getCount();
                                Double updsnum=Double.valueOf(updscale*updcount);
                                BigDecimal updsprice=commoditys.getSprice();
                                Integer updsid=1;
                                List<Map<String,Object>> sells=commodityService.sellSelect(null,null);
                                if (commodityService.sellSelect(null,updcid).size()==0){
                                    System.out.println("进入sell  if");
                                    if (sells.size()!=0){
                                        updsid= (Integer) sells.get(0).get("sid");
                                    }
                                    a=commodityService.sellInsert(new Sell(updsid,updcid,updsprice,updsnum));
                                }else {
                                    System.out.println("进入sell    else");
                                    double snum= (Double) commodityService.sellSelect(null,updcid).get(0).get("snum");
                                    System.out.println(snum);

                                    Integer oldsnum=((int)snum) %commoditys.getMids().getScale();
                                    System.out.println(oldsnum);

                                    Double newsnum=Double.valueOf(commoditys.getCount()*commoditys.getMids().getScale());
                                    System.out.println(newsnum);

                                    if (oldsnum!=0){
                                        newsnum=Double.valueOf(commoditys.getCount()*commoditys.getMids().getScale())+oldsnum-commoditys.getMids().getScale();
                                    }
                                    System.out.println(newsnum);

                                    a=commodityService.sellUpdSnum(updcid,newsnum);
                                }
                                if (upda==1){
                                    updb+=1;
                                    System.out.println(updb);

                                }
                            }
                        }
                    }
                }else {
                    IU=IU*1;
                    cid= commodities.get(commodities.size()-1).getCid()+1;
                }
            }
            if (IU!=2){
                Commodity commodity=new Commodity(cid,cname,new Classify(tid,null),cprice,null,
                        new Measurement(mid,null,null,null),count,
                        new Suppiler(sid,null,null,null,null,null,null,null),0);
                c=commodityService.commodityInsert(commodity);
            }
        }
        if (a+b+c==3){
            return "true";
        }else {
            return "false";
        }
    }



}
